package com.fx.zmlzml.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.entity.PcMotherboard;
import com.fx.zmlzml.exception.BusinessException;
import com.fx.zmlzml.exception.ErrorEnum;
import com.fx.zmlzml.service.PcMotherboardService;
import com.fx.zmlzml.util.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 电脑主板Controller
 * 提供RESTful API接口，用于操作电脑主板数据
 */
@RestController
@RequestMapping("/api/motherboard")
@Tag(name = "电脑主板管理", description = "提供电脑主板的CRUD操作及相关查询功能")
public class PcMotherboardController {
    
    private static final Logger logger = LoggerFactory.getLogger(PcMotherboardController.class);
    
    @Autowired
    private PcMotherboardService pcMotherboardService;
    
    /**
     * 分页获取电脑主板列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页获取电脑主板列表", description = "分页查询系统中的电脑主板信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PageInfo<PcMotherboard>> getPcMotherboardsByPage(
            @Parameter(description = "页码，默认为1", example = "1", required = false) @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认为15", example = "15", required = false) @RequestParam(defaultValue = "15") Integer pageSize) {
        logger.info("分页查询电脑主板列表请求，页码：{}，每页条数：{}", pageNum, pageSize);
        try {
            // 参数校验
            if (pageNum <= 0 || pageSize <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID,
                        MessageUtils.getMessage("common.validation.page_num") + "，" + 
                        MessageUtils.getMessage("common.validation.page_size"));
            }

            // 使用PageHelper进行分页
            PageHelper.startPage(pageNum, pageSize);
            List<PcMotherboard> list = pcMotherboardService.list();
            PageInfo<PcMotherboard> pageInfo = new PageInfo<>(list);

            logger.debug("分页查询电脑主板成功，总条数：{}", pageInfo.getTotal());
            return Result.i18nSuccess(pageInfo, "motherboard.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("分页查询电脑主板失败，页码：{}，每页条数：{}", pageNum, pageSize, e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_QUERY_FAILED.getCode(), 
                    "motherboard.query.fail", null);
        }
    }
    
    /**
     * 根据ID获取电脑主板详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取电脑主板详情", description = "根据唯一标识符查询电脑主板的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "记录不存在", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcMotherboard> getPcMotherboardById(@Parameter(description = "电脑主板ID", example = "1", required = true) @PathVariable Long id) {
        logger.info("根据ID查询电脑主板详情请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        MessageUtils.getMessage("common.validation.id"));
            }
            
            PcMotherboard motherboard = pcMotherboardService.getById(id);
            if (motherboard == null) {
                logger.warn("根据ID查询电脑主板失败，ID：{}，记录不存在", id);
                return Result.i18nError(ErrorEnum.MOTHERBOARD_NOT_FOUND.getCode(), 
                        "motherboard.not_found", null);
            }
            logger.debug("根据ID查询电脑主板成功，ID：{}", id);
            return Result.i18nSuccess(motherboard, "motherboard.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("根据ID查询电脑主板失败，ID：{}", id, e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_QUERY_FAILED.getCode(), 
                    "motherboard.query.fail", null);
        }
    }
    
    /**
     * 添加新的电脑主板
     */
    @PostMapping
    @Operation(summary = "添加新的电脑主板", description = "创建一条新的电脑主板记录")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效或缺失", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "添加失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcMotherboard> addPcMotherboard(@Parameter(description = "电脑主板信息", required = true) @RequestBody PcMotherboard motherboard) {
        logger.info("添加电脑主板请求，制造商：{}", motherboard.getManufacturer());
        try {
            // 参数校验
            if (motherboard == null) {
                throw new BusinessException(ErrorEnum.PARAM_MISSING, "请求体不能为空");
            }
            if (motherboard.getManufacturer() == null || motherboard.getManufacturer().trim().isEmpty()) {
                throw new BusinessException(ErrorEnum.PARAM_MISSING, "制造商不能为空");
            }
            
            motherboard.setCreatedTime(new Date());
            motherboard.setUpdatedTime(new Date());
            boolean saved = pcMotherboardService.save(motherboard);
            if (saved) {
                logger.info("添加电脑主板成功，ID：{}", motherboard.getId());
                return Result.i18nSuccess(motherboard, "motherboard.add.success", null);
            }
            logger.warn("添加电脑主板失败，制造商：{}", motherboard.getManufacturer());
            return Result.i18nError(ErrorEnum.MOTHERBOARD_ADD_FAILED.getCode(), 
                    "motherboard.add.fail", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("添加电脑主板异常，制造商：{}", motherboard.getManufacturer(), e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_ADD_FAILED.getCode(), 
                    "motherboard.add.fail", null);
        }
    }
    
    /**
     * 更新电脑主板信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新电脑主板信息", description = "根据ID更新电脑主板的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效或缺失", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "记录不存在", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcMotherboard> updatePcMotherboard(
            @Parameter(description = "电脑主板ID", example = "1", required = true) @PathVariable Integer id,
            @Parameter(description = "更新的电脑主板信息", required = true) @RequestBody PcMotherboard motherboard) {
        logger.info("更新电脑主板请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, "ID必须为正整数");
            }
            if (motherboard == null) {
                throw new BusinessException(ErrorEnum.PARAM_MISSING, "请求体不能为空");
            }
            
            motherboard.setId(id);
            motherboard.setUpdatedTime(new Date());
            boolean updated = pcMotherboardService.updateById(motherboard);
            if (updated) {
                logger.info("更新电脑主板成功，ID：{}", id);
                return Result.i18nSuccess(motherboard, "motherboard.update.success", null);
            }
            logger.warn("更新电脑主板失败，ID：{}", id);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_NOT_FOUND.getCode(), 
                    "motherboard.not_found", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("更新电脑主板异常，ID：{}", id, e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_UPDATE_FAILED.getCode(), 
                    "motherboard.update.fail", null);
        }
    }
    
    /**
     * 删除电脑主板
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除电脑主板", description = "根据ID删除电脑主板记录")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "记录不存在", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Void> deletePcMotherboard(@Parameter(description = "电脑主板ID", example = "1", required = true) @PathVariable Long id) {
        logger.info("删除电脑主板请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, "ID必须为正整数");
            }
            
            boolean deleted = pcMotherboardService.removeById(id);
            if (deleted) {
                logger.info("删除电脑主板成功，ID：{}", id);
                return Result.i18nSuccess("motherboard.delete.success", null);
            }
            logger.warn("删除电脑主板失败，ID：{}", id);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_NOT_FOUND.getCode(), 
                    "motherboard.not_found", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除电脑主板异常，ID：{}", id, e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_DELETE_FAILED.getCode(), 
                    "motherboard.delete.fail", null);
        }
    }
    
    /**
     * 根据制造商获取电脑主板列表
     */
    @GetMapping("/manufacturer/{manufacturer}")
    @Operation(summary = "根据制造商获取电脑主板列表", description = "查询指定制造商的所有电脑主板")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效或缺失", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<List<PcMotherboard>> getPcMotherboardsByManufacturer(@Parameter(description = "制造商名称", example = "ASUS", required = true) @PathVariable String manufacturer) {
        logger.info("根据制造商查询电脑主板列表请求，制造商：{}", manufacturer);
        try {
            // 参数校验
            if (manufacturer == null || manufacturer.trim().isEmpty()) {
                throw new BusinessException(ErrorEnum.PARAM_MISSING, "制造商不能为空");
            }
            
            QueryWrapper<PcMotherboard> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("manufacturer", manufacturer);
            List<PcMotherboard> motherboards = pcMotherboardService.list(queryWrapper);
            logger.debug("根据制造商查询电脑主板成功，制造商：{}，共{}条记录", manufacturer, motherboards.size());
            return Result.i18nSuccess(motherboards, "motherboard.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("根据制造商查询电脑主板失败，制造商：{}", manufacturer, e);
            return Result.i18nError(ErrorEnum.MOTHERBOARD_QUERY_FAILED.getCode(), 
                    "motherboard.query.fail", null);
        }
    }
}